import React, { useState, useRef, useEffect } from 'react'
import { Popup, PickerView, Button } from 'antd-mobile'
import { PickerColumnItem, PickerValue } from 'antd-mobile/es/components/picker-view'
import classNames from 'classnames'
import { areaList } from '@vant/area-data'
import style from './index.less'

interface LooseObjType<T = any> {
    [key: string]: T
}
interface AreaPickerProps {
    visible?: boolean
    className?: string
    onClose?: () => void
    onConfirm?: (val:{}) => void
    title?: string
}

const AreaPicker: React.FC<AreaPickerProps> = (props) => {
    const { visible, className, onClose, onConfirm, title } = props
    const { province_list, city_list, county_list } = areaList // 省市区

    // 变化的值
    const [value, setValue] = useState<PickerValue[]>(['', '', ''])
    // 确定的值（confirm 点击确定按钮后记录）
    const determinantVal = useRef<PickerValue[]>(['', '', ''])

    const [provinceList, setProvinceList] = useState<PickerColumnItem[]>([])
    const [cityList, setCityList] = useState<PickerColumnItem[]>([])
    const [countyList, setCountyList] = useState<PickerColumnItem[]>([])

    const classes = classNames(style['area-picker-popup'], className)

    // 处理地区数据
    const processAreaData = (source: LooseObjType): PickerColumnItem[] => {
        return [
            { label: '请选择', value: '' },
            ...Object.keys(source).map((key) => ({
                label: source[key],
                value: `${key}-${source[key]}`,
            }))
        ]
    }

    // 根据传入的值设置城市和区县列表
    const updateCityAndCountyList = (currentVal: PickerValue[]) => {
        const [provinceVal, cityVal] = currentVal
        const cityList = JSON.parse(JSON.stringify(city_list)) // 浅拷贝
        const countyList = JSON.parse(JSON.stringify(county_list))

        if (provinceVal) {
            const _pattern = new RegExp(`^${provinceVal.slice(0, 2)}`)
            for (const k in cityList) {
                if (!_pattern.test(k)) {
                    delete cityList[k]
                }
            }
            setCityList(processAreaData(cityList))
        } else {
            setCityList([])
        }

        if (cityVal) {
            const _pattern = new RegExp(`^${cityVal.slice(0, 4)}`)
            for (const k in countyList) {
                if (!_pattern.test(k)) {
                    delete countyList[k]
                }
            }
            setCountyList(processAreaData(countyList))
        } else {
            setCountyList([])
        }
    }

    // 点击确定按钮
    const handleConfirm = () => {
        determinantVal.current = [...value]
        onClose?.()
        const info ={
            areaCode:[...value].map(i => i?.split('-')[0])[2],
            shipmentPlace:[...value].map(i => i?.split('-')[1]).join('')
        }
        console.log(info);
        onConfirm && onConfirm(info)
    }

    // 滑动选择时，根据省筛选市 根据市筛选区县
    const handleChange = (val: PickerValue[]) => {
        updateCityAndCountyList(val)
        setValue(val)
    }

    // mounted时设置省列表
    useEffect(() => {
        setProvinceList(processAreaData(province_list))
    }, [])

    // 当弹框显示时设置上次点确定时的值和列表
    useEffect(() => {
        if (visible) {
            updateCityAndCountyList(determinantVal.current)
            setValue(determinantVal.current)
        }
    }, [visible])
    
    return (
        <Popup
            className={classes}
            visible={visible}
            onMaskClick={onClose}
        >
            <div className={style['popup-hd']}>
                <Button fill="none" onClick={onClose}>
                    取消
                </Button>
                <div className={style.title}>
                    {title}
                </div>
                <Button
                    fill="none"
                    onClick={handleConfirm}
                    className={style.true}
                >
                    确定
                </Button>
            </div>
            <div className={style['popup-bd']}>
                <PickerView
                    columns={[provinceList, cityList, countyList]}
                    value={value}
                    onChange={(val) => handleChange(val)}
                />
            </div>
        </Popup>
    )
}

export default AreaPicker
